/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.manager;

import br.com.foxline.clinicplus.entity.Cash;
import br.com.foxline.clinicplus.entity.ContaBancaria;
import br.com.foxline.clinicplus.entity.Operator;
import br.com.foxline.clinicplus.enums.TypeIncome;
import br.com.foxline.clinicplus.service.CashService;
import br.com.foxline.clinicplus.service.ContaBancariaServico;
import br.com.foxline.clinicplus.service.OperatorService;
import br.com.foxline.clinicplus.service.SystemUserService;
import br.com.foxline.clinicplus.util.Msg;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerCash implements Serializable {

    @EJB
    private CashService cashService;
    @EJB
    private SystemUserService systemUserService;
    @EJB
    private ContaBancariaServico contaBancariaServico;
    @EJB
    private OperatorService operatorService;
    private ContaBancaria contaBancaria;
    private ContaBancaria contaBancariaOrigem;
    private TypeIncome typeIncome;
    private Cash cash;
    private Date dateInitial;
    private Date dateFinal;
    private List<Cash> cashs;
    private BigDecimal total;

    @PostConstruct
    private void init() {

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        if (params.get("id") != null) {
            try {
                this.cash = cashService.find(Long.parseLong(params.get("id")));
                this.typeIncome = this.cash.getTypeIncome();
                this.contaBancaria = contaBancariaServico.find(this.cash.getContaBancaria().getId());
            } catch (Exception e) {
                Msg.messagemWarn();
            }
        } else {
            this.cash = new Cash();
        }
        this.cashs = new ArrayList<Cash>();
    }

    public List<ContaBancaria> autocompleteContaBancarias(String valor) {
        return contaBancariaServico.autocomplete(valor);
    }
    
    public List<Operator> autocompleteConvenios(String valor) {
        return operatorService.autocomplete(valor);
    }

    public Cash getCash() {
        return cash;
    }

    public void setCash(Cash cash) {
        this.cash = cash;
    }

    public void saldo() {
        cashs = cashService.searchCash(null, null, contaBancaria);
        total = cashService.searchValueCash(dateInitial, dateFinal, contaBancaria, null);
//        return cashService.sumCash(null);
    }

    public BigDecimal saldo(ContaBancaria contaBancaria, Date data) {
        return cashService.sumCash(contaBancaria, data);
    }
    
        
    public BigDecimal saldoAnterior(ContaBancaria contaBancaria, Date data) {
        return cashService.saldoAnterior(contaBancaria, data);
    }

    public BigDecimal despesasPorCaixa(ContaBancaria contaBancaria, Date data) {
        if (data != null) {
            dateInitial = data;
            dateFinal = data;
        } else {
            dateInitial = new Date();
            dateFinal = new Date();
        }
        Cash c = new Cash();
        c.setTypeIncome(typeIncome.D);
        return cashService.searchValueCash(dateInitial, dateFinal, contaBancaria, c);
    }

    public BigDecimal despesasPorCaixaPorDataPesquisa(ContaBancaria contaBancaria) {
        if (dateInitial != null) {
//            dateInitial = new Date();
//            dateFinal = new Date();
            Cash c = new Cash();
            c.setTypeIncome(typeIncome.D);
            return cashService.searchValueCash(dateInitial, dateFinal, contaBancaria, c);
        } else {
            return BigDecimal.ZERO;
        }
    }

    public void pesquisar() {
        cashs = cashService.searchCash(dateInitial, dateFinal, contaBancaria);
        total = cashService.searchValueCash(dateInitial, dateFinal, contaBancaria, null);
    }

    public void closeCash(BigDecimal value) {
        this.cash.setValue(value);

        if (cash.getValue().compareTo(BigDecimal.ZERO) == 1) {
            typeIncome = TypeIncome.C;
        } else {
            typeIncome = TypeIncome.D;
        }
        cash.setCloseCash(true);
        Calendar c = GregorianCalendar.getInstance();
        cash.setCreatAt(c.getTime());
        cash.setDescription("Fechamento automático");

        salvar();
    }

    /**
     * Fechamento de caixa, na tela de intervalo de datas
     *
     * @param value
     */
    public void fecharCaixaEmIntevaloDatas(BigDecimal value, Date data) {
//        if (dateInitial != null) {
        System.err.println("FECHAR CAIXA");
        this.cash.setValue(value);

        if (cash.getValue().compareTo(BigDecimal.ZERO) == 1) {
            typeIncome = TypeIncome.C;
        } else {
            typeIncome = TypeIncome.D;
        }
        cash.setCloseCash(true);
        
        Calendar c = GregorianCalendar.getInstance();
        c.setTime(data);
        c.set(GregorianCalendar.HOUR_OF_DAY, 18);
        cash.setCreatAt(c.getTime());
        
        cash.setDescription("Fechamento automático");

        salvar();
//        }
    }

    public void salvar() {
        try {
            if (contaBancaria != null && contaBancaria.getId() != null) {
                cash.setContaBancaria(contaBancaria);
            }
            cash.setTypeIncome(typeIncome);
            if (typeIncome == TypeIncome.D && cash.getValue() != null) {
                if (cash.getValue().compareTo(BigDecimal.ZERO) != -1) {
                    cash.setValue(cash.getValue().multiply(new BigDecimal("-1")));
                }
            }
            cash.setSystemUser(systemUserService.getCurrentUser());
            if (cash.getId() == null) {
                cashService.save(cash);
            } else {
                cashService.update(cash);
            }
            Msg.messagemInfo();
        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError();
        }
    }

    public List<SelectItem> selectTypeIncome() {
        List<SelectItem> list = new ArrayList<SelectItem>();

        for (TypeIncome ms : TypeIncome.values()) {
            if (ms != TypeIncome.R) {
                list.add(new SelectItem(ms, ms.getName()));
            }
        }
        return list;
    }

    public Date getDateFinal() {
        return dateFinal;
    }

    public void setDateFinal(Date dateFinal) {
        this.dateFinal = dateFinal;
    }

    public Date getDateInitial() {
        return dateInitial;
    }

    public void setDateInitial(Date dateInitial) {
        this.dateInitial = dateInitial;
    }

    public List<Cash> getCashs() {
        return cashs;
    }

    public void setCashs(List<Cash> cashs) {
        this.cashs = cashs;
    }

    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }

    public TypeIncome getTypeIncome() {
        return typeIncome;
    }

    public void setTypeIncome(TypeIncome typeIncome) {
        this.typeIncome = typeIncome;
    }

    public ContaBancaria getContaBancaria() {
        return contaBancaria;
    }

    public void setContaBancaria(ContaBancaria contaBancaria) {
        this.contaBancaria = contaBancaria;
    }
    
    public Cash cashToday(Date data) {
        if (data != null) {
            return cashService.existCashToday(data);
        } else {
            return cashService.existCashToday(new Date());
        }
    }
    
    public boolean existCashToday(Date data) {
        if (data != null) {
            return cashService.existCashToday(data) != null ? true:false;
        } else {
            return cashService.existCashToday(new Date())  != null ? true:false;
        }
    }

    public boolean existCashTodaySearch(Date date) {
        if (date != null) {
            return cashService.existCashToday(date) != null ? true:false;
        }
        return false;
    }

    public boolean verifyMaster() {
        return systemUserService.verifyMaster();
    }

    public ContaBancaria getContaBancariaOrigem() {
        return contaBancariaOrigem;
    }

    public void setContaBancariaOrigem(ContaBancaria contaBancariaOrigem) {
        this.contaBancariaOrigem = contaBancariaOrigem;
    }

    public void transferir() {
        try {
            
            if(cash != null && cash.getId() != null){
                return;
            }
            
            //DESTINO OU CREDITO
            if (contaBancaria != null && contaBancaria.getId() != null) {
                cash.setContaBancaria(contaBancaria);
            }
            cash.setTypeIncome(TypeIncome.C);
            cash.setSystemUser(systemUserService.getCurrentUser());
            cashService.save(cash);
            
            //ORIGEM OU DEBITO
            cash.setId(null);
            if (contaBancariaOrigem != null && contaBancariaOrigem.getId() != null) {
                cash.setContaBancaria(contaBancariaOrigem);
            }
            cash.setTypeIncome(TypeIncome.D);
            if (cash.getValue() != null) {
                if (cash.getValue().compareTo(BigDecimal.ZERO) != -1) {
                    cash.setValue(cash.getValue().multiply(new BigDecimal("-1")));
                }
            }
            cashService.save(cash);
            Msg.messagemInfo();
        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError();
        }
    }
}
